# -*- coding:utf-8 -*-

# @Time : 2023/5/9 14:43
# @Author : 快乐的小猴子
# @Version : 
# @Function :


import os
import json
import requests
from conf import setting
from SetProxies import SetProxies


class GwTjiaDaias:

    def hand_url(self, if_flg):
        url = setting.gw_url.format(if_flg)
        return url

    def send(self, url):
        session = requests.Session()
        with open(setting.base_infos_list[19], 'r', encoding='UTF-8') as fp:
            cookies = json.loads(fp.read())
            for cookie in cookies:
                c = {cookie['name']: cookie['value']}
                session.cookies.update(c)
        # resp = session.get(url, headers=setting.headers, proxies=setting.proxies)
        resp = session.get(url, headers=setting.headers)
        resp.encoding = 'UTF-8'
        datas = json.loads(resp.text.split('(', 1)[1][:-1])
        return datas

    def save_gw_file(self, flag, datas):
        num = 1
        if flag == 'N':
            file_name = os.path.join(os.path.expanduser("~"), setting.base_infos_list[0]) + setting.base_infos_list[
                18] + setting.base_infos_list[20]
        else:
            file_name = os.path.join(os.path.expanduser("~"), setting.base_infos_list[0]) + setting.base_infos_list[
                18] + setting.base_infos_list[21]
        with open(file_name, 'w', encoding='UTF-8') as fp:
            print(setting.base_infos_list[3] + setting.base_infos_list[24])
            fp.write(setting.base_infos_list[22])
            for i in range(0, len(datas['FROMOFLIGHTS'])):
                from_depctiyname_en = datas['FROMOFLIGHTS'][i]['DEPCTIYNAME_EN']
                from_depctiyname_zn = datas['FROMOFLIGHTS'][i]['DEPCTIYNAME_ZH']
                from_flight = datas['FROMOFLIGHTS'][i]['FLIGHT']
                for j in range(0, len(from_flight)):
                    depdate = from_flight[j]['DEPDATE']
                    arrcityname_en = from_flight[j]['ARRCTIYNAME_EN']
                    arrcityname_zn = from_flight[j]['ARRCTIYNAME_ZH']
                    minprice = from_flight[j]['MINPRICE'] + from_flight[j]['money']
                    print(num, from_depctiyname_en, from_depctiyname_zn, arrcityname_en, arrcityname_zn,
                          depdate, minprice)
                    fp.write(str(
                        num) + '|' + from_depctiyname_zn + '|' + arrcityname_zn + '|' + depdate + '|' + minprice + '\n')
                    num += 1
            print(setting.base_infos_list[23].format(file_name))

    def get_gw_datas(self):
        for i in range(0, len(setting.if_flg)):
            gw_url = self.hand_url(setting.if_flg[i])
            datas = self.send(gw_url)
            self.save_gw_file(setting.if_flg[i], datas)
